<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="班级名称">
              <a-input placeholder="请输入班级名称" v-model="queryParam.className"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="班级类型">
              <j-dict-select-tag placeholder="请选择班级类型" v-model="queryParam.classType" dictCode="class_type"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'management:sk_class:add'">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('班级信息表')" v-has="'management:sk_class:exportXls'">导出</a-button>
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <a-button @click="handleSetAreaTime" type="primary" icon="edit" v-has="'management:sk_class:area'">区角活动时间设置</a-button>
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" >
          <!-- <a-menu-item key="1" @click="graduateBath"><a-icon type="user" />毕业</a-menu-item> -->
          <a-menu-item key="2" @click="batchDel" v-has="'management:sk_class:deleteBatch'"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a-space>

            <a @click="handleEdit(record)" v-has="'management:sk_class:edit'">编辑</a>
            <a @click="handleTeacherInit(record)" v-has="'management:sk_class:teacher'">教师设置</a>
            <a @click="handleDeviceInit(record)" v-has="'management:sk_class:device'">班级设备</a>
            <a @click="handleSetAreaTimeForClass(record)" v-has="'management:sk_class:area'">区角活动时间设置</a>
            <a-popconfirm title="确定毕业吗?" @confirm="() => graduate(record)" v-if="record.classType == 4">
              <a>毕业</a>
            </a-popconfirm>
            <a @click="promotion(record)" v-else>升班</a>
            <a-dropdown>
              <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item v-has="'management:sk_class:info'">
                  <a @click="handleDetail(record)">详情</a>
                </a-menu-item>
                <a-menu-item v-has="'management:sk_class:delete'">
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </a-space>
        </span>

      </a-table>
    </div>
    <!-- <j-select-teacher placeholder="请选择教师" ref="selectTeacher" :selectTeacher="true" :multiple="true" v-model="teacherId"/> -->
    <!-- <j-select-device placeholder="请选择设备" ref="selectDevice" :selectDevive="true" :multiple="true" v-model="DeviveId"/> -->
    <sk-class-modal ref="modalForm" @ok="modalFormOk"></sk-class-modal>
    <sk-class-set-area-modal ref="setAreaForm"></sk-class-set-area-modal>
    <sk-class-select-teacher ref="selectTeacher" ></sk-class-select-teacher>
    <a-modal
      title="升班"
      :visible="modalVisible"
      @cancel="handleCancel"
    >
      <template slot="footer">
        <a-button @click="handleCancel">
          取消
        </a-button>
        <a-popconfirm title="升班后不可更改，是否确定?" @confirm="handleSubmit">
          <a-button  type="primary" :loading="confirmLoading" >
            确定
          </a-button>
        </a-popconfirm>
      </template>
      <a-form-model layout="inline" ref="dataForm" :model="dataForm" :rules="dataRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="班级" prop="toClassId"  style="width:100%;">
          <a-select v-model="dataForm.toClassId" style="width: 100%" @change="handleChange" placeholder="请选择要升入的班级">
            <a-select-option v-for="item in classList" :key="item.id" :value="item.id">{{ item.className }}</a-select-option>
          </a-select> 
          <!-- <j-dict-select-tag placeholder="请选择要升入的班级" v-model="dataForm.toClassId" dictCode="sk_class,class_name,id,del_flag = 0 order by sort_no asc"/> -->
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import SkClassModal from './modules/SkClassModal.vue'
  import SkClassSetAreaModal from './modules/SkClassSetAreaModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import JSelectTeacher from '@comp/jeecgbiz/JSelectTeacher'
  import JSelectDevice from '@comp/jeecgbiz/JSelectDevice'
  import { getTeache } from "@/api/management.js";
  import { getAction,httpAction } from "@/api/manage.js";
  import SkClassSelectTeacher from "./modules/SkClassSelectTeacher.vue";
  export default {
    name: 'SkClassList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      SkClassModal,
      SkClassSetAreaModal,
      JSelectTeacher,
      JSelectDevice,
      SkClassSelectTeacher
    },
    data () {
      return {
        modalVisible:false,
        confirmLoading:false,
        dataForm:{},
        dataRules:{
          toClassId: [{ required: true, message: '请选择要升入的班级'}],
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        classList:[],
        description: 'sk_class管理页面',
        teacherId:"",
        DeviveId:"",
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'班级名称',
            align:"center",
            dataIndex: 'className'
          },
          {
            title:'班级类型',
            align:"center",
            dataIndex: 'classType_dictText'
          },
          {
            title:'排序',
            align:"center",
            sorter:true,
            dataIndex: 'sortNo'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:207,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/management/skClass/page",
          delete: "/management/skClass/delete",
          deleteBatch: "/management/skClass/deleteBatch",
          exportXlsUrl: "/management/skClass/exportXls",
          importExcelUrl: "management/skClass/importExcel",
          
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
      this.getClassLsit(null);
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      initDictConfig(){
        this.isorter.column = 'sortNo';
        this.isorter.order = 'asc';
      },
      getClassLsit(classType){
        const url = "/management/skClass/getClassList"
        const params = {
          id:classType
        }
        getAction(url,params).then((res)=>{
          if(res.success){
            this.classList = res.result;
            console.log(this.classList);
          } else {
           this.$message.warning(res.message);
          }
        }).catch((error)=>{
          console.error(error);
        })
      },
      handleClass(id){
        return this.classList.find(item=>id == item.id);
      },
      
      // 毕业
      graduate(record){
        let classItem = this.handleClass(record.id);
        if (classItem.studentCount == 0 ) {
          this.$message.warning("当前班级没有儿童，无需毕业");
        }else{
          const url = "/management/skStudent/graduateStudentByClass"
          getAction(url,{classIds:record.id}).then((res)=>{
            if(res.success){
              this.loadData();
              this.$message.success("操作成功！");
            } else {
              this.$message.warning(res.message);
            }
          }).catch((error)=>{
            console.error(error);
          })
        }
      },
      // graduateBath(){
      //   if (this.selectedRowKeys.length <= 0) {
      //     this.$message.warning('请选择一条记录！');
      //     return;
      //   } else {
      //     var ids = "";
      //     for (var a = 0; a < this.selectedRowKeys.length; a++) {
      //       ids += this.selectedRowKeys[a] + ",";
      //     }
      //     var that = this;
      //     this.$confirm({
      //       title: "确认毕业",
      //       content: "是否确定毕业?",
      //       onOk: function () {
      //         that.loading = true;
      //         const url = "/management/skStudent/graduateStudentByClass"
      //         getAction(url, {classIds: ids}).then((res) => {
      //           if (res.success) {
      //             //重新计算分页问题
      //             that.reCalculatePage(that.selectedRowKeys.length)
      //             that.$message.success(res.message);
      //             that.loadData();
      //             that.onClearSelected();
      //           } else {
      //             that.$message.warning(res.message);
      //           }
      //         }).finally(() => {
      //           that.loading = false;
      //         });
      //       }
      //     });
      //   }
      // },
      // 选择升班班级
      handleChange(e){
        let classItem = this.handleClass(e);
        if (classItem.studentCount > 0 ) {
          this.$message.warning("选择的班级存在儿童，请先将班级升班或毕业");
          this.dataForm.toClassId = undefined;
        }
      },
      // 升班
      promotion(record){
        let classItem = this.handleClass(record.id);
        if (classItem.studentCount == 0 ) {
          this.$message.warning("当前班级暂无儿童，无需升班");
        }else{
          this.getClassLsit(Number(record.classType) + 1)
          this.dataForm.fromClassId = record.id;
          this.modalVisible = true;
        }
      },
      handleSubmit(){
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.confirmLoading = true;
            const url = "/management/skStudent/upStudentClass"
            const data = this.dataForm
            console.log(data);
            getAction(url,data).then((res)=>{
              if(res.success){
                this.$message.success(res.message);
              } else {
                this.$message.warning(res.message);
              }
              this.confirmLoading = false;
            }).catch((error)=>{
              this.confirmLoading = false;
              console.error(error);
            })
          }
        })
      },
      handleCancel(){
        this.getClassLsit(null)
        this.modalVisible = false;
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'className',text:'班级名称',dictCode:''})
        fieldList.push({type:'int',value:'classType',text:'班级类型',dictCode:'class_type'})
        this.superFieldList = fieldList
      },
      handleTeacherInit(record){
        const json = {
          classId:record.id,
          list:"/management/teacher/list",
          info:"/management/skClass/getTeacher",
          submit:"/management/skClass/setTeacher",
          label:"教师名称",
          title:"教师设置",
          modelCode:"teacherIds",
          idCode:"id",
          nameCode:"realname"
        }
        this.$refs.selectTeacher.init(json)
      },
      handleDeviceInit(record){
        const json = {
          classId:record.id,
          list:"/management/skDevice/list",
          info:"/management/skClass/getDevice",
          submit:"/management/skClass/setDevice",
          label:"设备名称",
          title:"设备设置",
          modelCode:"deviceIds",
          idCode:"id",
          nameCode:"deviceName"
        }
        this.$refs.selectTeacher.init(json)
      },
      // 设备设置
      // async handleDeviceInit(record){
      //   await this.getDeviceId(record.id);
      //   await this.$refs.selectDevice.open(record)
      // },
      // 获取设备
      // getDeviceId(id){
      //   return new Promise((resolve, reject) => {
      //     let data = {
      //       classId:id
      //     }
      //     let url = "/management/skClass/getDevice"
      //     getAction(url,data).then((res)=>{
      //       this.DeviveId = res.result.join(",");
      //       resolve()
      //     }).catch((error)=>{
      //       console.error(error);
      //     })
      //   })
      // },

      // 教师设置
      // async handleTeacherInit(record){
      //   await this.getTeacherId(record.id);
      //   await this.$refs.selectTeacher.open(record);
      // },
      
      // 获取教师id
      // getTeacherId(id){
      //   return new Promise((resolve, reject) => {
      //     let data = {
      //       classId:id
      //     }
      //     const url = "/management/skClass/getTeacher"
      //     getAction(url,data).then((res)=>{
      //       this.teacherId = res.result.join(",");
      //       resolve()
      //     }).catch((error)=>{
      //       console.error(error);
      //     })
      //   })
      // },
      handleSetAreaTime() {
        this.$refs.setAreaForm.title = '全园区角活动时间设置';
        this.$refs.setAreaForm.add()
      },
      handleSetAreaTimeForClass(record) {
        this.$refs.setAreaForm.title = record.className + '区角活动时间设置';
        this.$refs.setAreaForm.edit(record)
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>